package com.lagou.test04.test05;

import java.io.*;
import java.net.Socket;
import java.util.List;

public class ServerThread extends Thread {

    private Socket socket;

    private List<Socket> socketList;

    public ServerThread(Socket socket, List<Socket> socketList) {
        this.socket = socket;
        this.socketList = socketList;
    }

    @Override
    public void run() {
        PrintStream stream = null;
        BufferedReader reader = null;
        try {
            while(true){
                reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String str =  reader.readLine();

                if ("bye".equalsIgnoreCase(str)) {
                    System.out.println("聊天结束！");
                    break;
                }

                for (Socket socket1:socketList ) {
                    System.out.println(socket.getInetAddress()+"客户端发送消息为--->"+str);
                    System.out.println("socket1---->"+socket1.getRemoteSocketAddress());
                    stream = new PrintStream(socket1.getOutputStream());
                    stream.println(str);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            stream.close();
        }

    }
}
